package com.qfedu.edu.service.impl;

import com.qfedu.edu.constance.Constance;
import com.qfedu.edu.service.ITokenService;
import io.jsonwebtoken.*;
import org.joda.time.DateTime;

import java.util.concurrent.TimeUnit;

/**
 * @author wangchen
 * @title: TokenService
 * @projectName cd-fy-2401-third-project-parent
 * @description: TODO
 * @date 2024/9/13  15:25
 */
public class TokenService implements ITokenService {

    //这个是token的过期时间
    private Integer expire;

    //签名
    private String sign;

    //签名算法
    private SignatureAlgorithm signatureAlgorithm=SignatureAlgorithm.HS256;

    //压缩模式
    private CompressionCodec compressionCodec=CompressionCodecs.GZIP;

    public void setExpire(Integer expire) {
        this.expire = expire;
    }

    public void setSign(String sign) {
        this.sign = sign;
    }

    @Override
    public String createToken(String id, String username) {
        String token = Jwts.builder()
                .setId(String.valueOf(id))
                .setSubject(username)
                .setExpiration(DateTime.now().plusDays(Math.toIntExact(expire)).toDate())
                .signWith(signatureAlgorithm,sign)
                .compressWith(compressionCodec)
                .compact();
        System.out.println("生成的token信息如下:" + token);
        return token;
    }

    @Override
    public boolean verify(String token) {
        try {
            Jwts.parser()
                    .setSigningKey(sign)
                    .parseClaimsJws(token);
            return true;
        } catch (Exception err) {
            return false;
        }
    }

    @Override
    public String refreshToken(String token) {
        //这里需要将原始token的信息取出来从新生成一个新的token
        try {
            Jws<Claims> jws = Jwts.parser()
                    .setSigningKey(sign)
                    .parseClaimsJws(token);
            String id = jws.getBody().getId();
            String username = jws.getBody().getSubject();
            //然后从新生成token
            return createToken(id, username);
        } catch (Exception err) {
            throw new RuntimeException(err);
        }
    }

    @Override
    public Jws<Claims> parseToken(String token) {
        try {
            Jws<Claims> jws = Jwts.parser()
                    .setSigningKey(sign)
                    .parseClaimsJws(token);
            return jws;
        } catch (Exception err) {
            throw new RuntimeException(err);
        }
    }
}
